﻿using ArmyCreator;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace ArmyCreator.WebCalls
{
    public class Caller
    {
        private static Uri baseUri = new Uri("http://192.168.1.10/json/");

        private string completeRelativeUri;
        private CallerResult result;
        private bool isFinished;

        public Caller()
        {
            result = null;
            isFinished = false;
        }

        private Uri buildUri(string relativeUri, Dictionary<string, object> parameters)
        {
            string completeRelativeUri = relativeUri;
            string separator = "?";

            foreach (var key in parameters.Keys)
            {
                completeRelativeUri += separator + key + "=" + parameters[key];
                separator = "&";
            }

            return new Uri(Caller.baseUri, completeRelativeUri);
        }

        public async Task<CallerResult> Call(string relativeUri, Dictionary<string, object> parameters)
        {
            if (!isFinished)
            {
                Uri completeUri = buildUri(relativeUri, parameters);
                HttpClient client = new HttpClient();
                client.Timeout = TimeSpan.FromMilliseconds(5000);

                try
                {
                    string content = await client.GetStringAsync(completeUri);

                    this.result = CallerResult.Create(content);
                }
                catch (Exception exception)
                {
                    Console.Error.WriteLine(exception.Message);
                    this.result = CallerResult.CreateError(exception.Message);
                }
                finally
                {
                    isFinished = true;
                }
            }

            return this.result;
        }
    }
}
